﻿#include "emotion.h"
#include <string>
#include <iostream>

using namespace std;

#ifdef WIN32
	const char sep = '\\';
#else
	const char sep = '/';
#endif



std::string
emotion_CpuInfer (const std::string &model_dir, const cv::Mat &image_file)
{
	auto model_file = model_dir + sep + "model.pdmodel";
	auto params_file = model_dir + sep + "model.pdiparams";
	auto config_file = model_dir + sep + "inference.yml";
	auto option = fastdeploy::RuntimeOption();
	option.UseCpu();
	auto model = fastdeploy::vision::classification::PaddleClasModel (
	                 model_file, params_file, config_file, option);
	std::string result;
	if (!model.Initialized()) {
		std::cerr << "Failed to initialize." << std::endl;
		result = "Failed to initialize.";
		return result;
	}
	
	
	auto im = image_file;
	fastdeploy::vision::ClassifyResult res;
	if (!model.Predict (im, &res)) {
		std::cerr << "Failed to predict." << std::endl;
		result = "Failed to initialize.";
		return result;
	}
	
	// print res
	std::cout << res.Str() << std::endl;
	return res.Str();
}




std::string
emotion_GpuInfer (const std::string &model_dir, const cv::Mat &image_file)
{
	auto model_file = model_dir + sep + "model.pdmodel";
	auto params_file = model_dir + sep + "model.pdiparams";
	auto config_file = model_dir + sep + "inference.yml";
	auto option = fastdeploy::RuntimeOption();
	option.UseGpu();
	
	auto model = fastdeploy::vision::classification::PaddleClasModel (
	                 model_file, params_file, config_file, option);
	std::string result;
	if (!model.Initialized()) {
		std::cerr << "Failed to initialize." << std::endl;
		result = "Failed to initialize.";
		return result;
	}
	
	auto im = image_file;
	
	fastdeploy::vision::ClassifyResult res;
	if (!model.Predict (im, &res)) {
		std::cerr << "Failed to predict." << std::endl;
		result = "Failed to initialize.";
		return result;
	}
	
	// print res
	std::cout << res.Str() << std::endl;
	return res.Str();
}




int
emotion_infer_by_camera (const std::string &device, const std::string &model_dir,
                         const std::string &window_name = "video")
{
	cv::VideoCapture cap (0);
	std::string result;
	
	if (!cap.isOpened()) {
		std::cout << "open camera failed!" << std::endl;
		return 0;
	}
	cv::namedWindow (window_name);
	
	while (1) {
		time_t t_now = time (0);
		
		cv::Mat frame;
		cap >> frame;
		if (frame.empty()) {
			return 0;
		}
		
		cv::imshow (window_name, frame);
		
		emotion_CpuInfer (model_dir, frame);
		if (device == "gpu") {
			cv::imshow (window_name, frame);
			result = emotion_GpuInfer (model_dir, frame);
		} else {
			cv::imshow (window_name, frame);
			result = emotion_CpuInfer (model_dir, frame);
		}
		std::cout << "emotion此帧共消耗" << (time (0) - t_now) << "秒" << std::endl;
		if (cv::waitKey (30) >= 0)
			break;
	}
	cap.release();
	return 1;
}